import threading
import os
import shutil
import tkinter as tk
from tkinter import filedialog
from tkinter.messagebox import showinfo

class Controller:
    # 导入UI类后，替换以下的 object 类型，将获得 IDE 属性提示功能
    ui: object
    def __init__(self):
        self.monitor_running = None
    def init(self, ui):
        self.ui = ui
        # TODO 组件初始化 赋值操作
    def choosePatha(self,evt):
        if self.monitor_running == True:
            return False
        directory_path = filedialog.askdirectory(
            title="选择文件夹"
        )
        # 显示选定的文件夹路径
        if directory_path:
            # print("选择的文件夹:", directory_path)
            # 更新界面或其他逻辑
            self.ui.tk_input_m0c6lpcn.delete(0, tk.END)
            self.ui.tk_input_m0c6lpcn.insert(0, directory_path)

    def choosePathb(self, evt):
        if self.monitor_running == True:
            return False
        directory_path = filedialog.askdirectory(
            title="选择文件夹"
        )
        # 显示选定的文件夹路径
        if directory_path:
            # print("选择的文件夹:", directory_path)
            # 更新界面或其他逻辑
            self.ui.tk_input_m0c6n6vi.delete(0, tk.END)
            self.ui.tk_input_m0c6n6vi.insert(0, directory_path)

    def startCopy(self,evt):
        if self.monitor_running == True:
            return # 如果监控已经在运行，则不执行任何操作
        fromPath = self.ui.tk_input_m0c6lpcn.get()
        savePath = self.ui.tk_input_m0c6n6vi.get()
        if fromPath == "" or savePath == "":
            showinfo(title="提示", message="两个路径都需要输入！")
            return False
        if fromPath in savePath:
            showinfo(title="提示", message="保存的路径不能选择到需要复制的文件夹内！")
            return False

        self.stop_event = threading.Event()
        self.thread = threading.Thread(target=self.update_counter, args=(fromPath,savePath))
        self.thread.daemon = True
        self.thread.start()

        self.ui.tk_button_m0c6lvy7.config(state=tk.DISABLED)
        self.ui.tk_button_m0c6nb3j.config(state=tk.DISABLED)
        self.ui.tk_button_m0c7djh2.config(state=tk.DISABLED)
        self.ui.tk_input_m0c6lpcn.config(state="readonly")
        self.ui.tk_input_m0c6n6vi.config(state="readonly")
        self.monitor_running = True

    def update_counter(self, fromPath,savePath):
        self.CreateDir(savePath)
        fileNum = self.count_files_in_directory(fromPath)
        self.ui.tk_progressbar_m0d8ueyu.config(length=fileNum,maximum=fileNum)
        self.ui.tk_progressbar_m0d8ueyu["value"] = 0
        self.ui.update()
        self.CopyFile(fromPath, savePath, fileNum)
        successfulText = "成功复制了" + str(fileNum) + "个文件"
        self.ui.tk_label_m0dhb051.config(text=successfulText)
        showinfo(title="提示", message="复制成功！")
        # 按钮启用
        self.ui.tk_button_m0c6lvy7.config(state=tk.NORMAL)
        self.ui.tk_button_m0c6nb3j.config(state=tk.NORMAL)
        self.ui.tk_button_m0c7djh2.config(state=tk.NORMAL)
        self.ui.tk_input_m0c6lpcn.config(state="normal")
        self.ui.tk_input_m0c6n6vi.config(state="normal")
        self.monitor_running = False
        self.stop_event.set()  # 设置停止事件
        self.stop_event.clear()
        #置0
        self.ui.tk_progressbar_m0d8ueyu["value"] = 0
        self.ui.update()
        return True

    def count_files_in_directory(self,directory_path):
        # 初始化文件计数
        file_count = 0
        # 使用 os.walk 遍历文件夹及其子目录
        for root, dirs, files in os.walk(directory_path):
            # 对于每个目录，累加文件数量
            file_count += len(files)
        # 返回文件总数
        return file_count

    def CopyFile(self,filepath, newPath, fileNum):
        # 获取当前路径下的文件名，返回List
        fileNames = os.listdir(filepath)
        for file in fileNames:
            # 将文件命加入到当前文件路径后面
            newDir = filepath + '/' + file
            # 如果是文件
            if os.path.isfile(newDir):
                newFile = newPath + '/'+ file
                shutil.copyfile(newDir, newFile)
                self.ui.tk_progressbar_m0d8ueyu["value"] += 1
                self.ui.update()
                successfulText = "进度：" + str(self.ui.tk_progressbar_m0d8ueyu["value"]) + " / " + str(fileNum)
                self.ui.tk_label_m0dhb051.config(text=successfulText)
            # 如果不是文件，递归这个文件夹的路径
            else:
                self.CopyFile(newDir, newPath, fileNum)

    def CreateDir(self,path):
        isExists = os.path.exists(path)
        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            os.makedirs(path)
            # print(path + ' 目录创建成功')
        # else:
            # 如果目录存在则不创建，并提示目录已存在
            # print(path + ' 目录已存在')
